var util = require('../../utils/util.js');
var api = require('../../config/api.js');
const pay = require('../../services/pay.js');
const app = getApp()

Page({
    data: {
        //用户信息
        userOneList:[],
        //用户下单商品信息
        goodsOneList:[],
        //商品数量
        number:0,
        checkedGoodsList: [],
        checkedAddress: {},
        goodsTotalPrice: 0.00, //商品总价
        freightPrice: 0.00, //快递费
        orderTotalPrice: 0.00, //订单总价
        actualPrice: 0.00, //实际需要支付的总价
        addressId: 0,
        goodsCount: 0,
        postscript: '',
        outStock: 0,
        orderdata:[],
        sumgoodsprice:0,
        sumpriceend:0,
        payMethodItems: [{
                name: 'offline',
                value: '线下支付'
            },
            {
                name: 'online',
                value: '在线支付',
                checked: 'true'
            },
        ],
        payMethodsafe: [{
          name: 'offsafe',
          value: '无运费险',
          checked: 'true'
      },
      {
          name: 'onsafe',
          value: '运费险',
          
      },
  ],
        payMethod:1,
        safeMethod:0,
        booleanbto:true
    },
    payChange(e){
        let val = e.detail.value;
        if(val == 'offline'){
            this.setData({
                payMethod:0
            })
        }
        else{
            this.setData({
                payMethod:1
            })
        }
    },
    // 运费险
    safeChange(e){
      let that=this
      let val = e.detail.value;
      
      if(val == 'offsafe'){
        
          this.setData({
              safeMethod:0,
              sumpriceend:that.data.sumgoodsprice
          })
      }
      else{
        
          this.setData({
              safeMethod:1,
              sumpriceend:(that.data.sumgoodsprice*1.03).toFixed(2)
          })
      }
    },
    toGoodsList: function (e) {
      let goodId = this.data.goodsOneList.goodId;
      wx.navigateTo({
          url: '/pages/ucenter/goods-list/index?id=' + goodId,
      });
    },
    toSelectAddress: function () {
        wx.navigateTo({
            url: '/pages/ucenter/address/index?type=1',
        });
    },
    toAddAddress: function () {
        wx.navigateTo({
            url: '/pages/ucenter/address-add/index',
        })
    },
    bindinputMemo(event) {
        let postscript = event.detail.value;
        this.setData({
            postscript: postscript
        });
    },
    onLoad: function (options) {
      
        let orderFrom = options.orderFrom;
        let that=this
        if (options.data){
          this.setData({
            orderdata: JSON.parse(decodeURI(options.data))
          })
        }
        this.setData({
          goodsOneList:that.data.orderdata.checkedProduct,
          userOneList:that.data.orderdata.userInfo,
          number:that.data.orderdata.number 
        })
        if(that.data.userOneList.userPhone==''){
          this.setData({
            booleanbto:false
          })
        }
        let addType = that.data.orderdata.addType;
        console.log(that.data.userOneList)
        console.log(that.data.goodsOneList)
        
        this.setData({
          sumgoodsprice: (that.data.goodsOneList.goodPrice)*(that.data.number)
      })
      this.setData({
        sumpriceend:that.data.sumgoodsprice
    })
      
        if (addType != undefined) {
            this.setData({
                addType: addType
            })
        }
        if (orderFrom != undefined) {
            this.setData({
                orderFrom: orderFrom
            })
        }
    },
    onUnload: function () {
        
        wx.removeStorageSync('addressId');
    },
    onShow: function () {
        // 页面显示
        // TODO结算时，显示默认地址，而不是从storage中获取的地址值
        try {
            var addressId = wx.getStorageSync('addressId');
            if (addressId == 0 || addressId == '') {
                addressId = 0;
            }
            this.setData({
                'addressId': addressId
            });
        } catch (e) {}
        // this.getCheckoutInfo();
        this.getuser();
        

    },
    getuser(){
      console.log(wx.getStorageSync('userOneInfo'))
    },
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading()
        try {
            var addressId = wx.getStorageSync('addressId');
            if (addressId == 0 || addressId == '') {
                addressId = 0;
            }
            this.setData({
                'addressId': addressId
            });
        } catch (e) {
            // Do something when catch error
        }
        this.getCheckoutInfo();
        wx.hideNavigationBarLoading() //完成停止加载
        wx.stopPullDownRefresh() //停止下拉刷新
    },
    getCheckoutInfo: function () {
        let that = this;
        
        let addressId = that.data.addressId;
        let orderFrom = that.data.orderFrom;
        let addType = that.data.addType;
        util.request(api.CartCheckout, {
            addressId: addressId,
            addType: addType,
            orderFrom: orderFrom,
            type: 0
        }).then(function (res) {
            if (res.errno === 0) {
                let addressId = 0;
                if (res.data.checkedAddress != 0) {
                    addressId = res.data.checkedAddress.id;
                }
                that.setData({
                    checkedGoodsList: res.data.checkedGoodsList,
                    checkedAddress: res.data.checkedAddress,
                    actualPrice: res.data.actualPrice,
                    addressId: addressId,
                    freightPrice: res.data.freightPrice,
                    goodsTotalPrice: res.data.goodsTotalPrice,
                    orderTotalPrice: res.data.orderTotalPrice,
                    goodsCount: res.data.goodsCount,
                    outStock: res.data.outStock
                });
                let goods = res.data.checkedGoodsList;
                wx.setStorageSync('addressId', addressId);
                if (res.data.outStock == 1) {
                    util.showErrorToast('有部分商品缺货或已下架');
                } else if (res.data.numberChange == 1) {
                    util.showErrorToast('部分商品库存有变动');
                }
            }
        });
    },
    // TODO 有个bug，用户没选择地址，支付无法继续进行，在切换过token的情况下
    submitOrder: function (e) {
        let that=this
        if (this.data.addressId <= 0) {
            util.showErrorToast('请选择收货地址');
            return false;
        }
        // let addressId = this.data.addressId;
        // let postscript = this.data.postscript;
        // let freightPrice = this.data.freightPrice;
        // let actualPrice = this.data.actualPrice;
        wx.showLoading({
            title: '',
            mask:true
        })
        let safeMethod=that.data.safeMethod
        console.log("我再这儿")
        console.log(that.data.goodsOneList.createUser)
        if(safeMethod==0){
          let uandubOrders={
            userId:that.data.userOneList.userId,//下单用户id
            uubOdBusinessId:that.data.goodsOneList.createUser,//商家id
            goodId:that.data.goodsOneList.goodId,//下单商品id
            // uubOdAddress://用户地址
            uubOdActualprice:that.data.sumgoodsprice,//实付价格
            createUser:that.data.userOneList.userId,
            updateUser:that.data.userOneList.userId,//创建人和修改人
        }
        util.request(api.saveOrder,uandubOrders, 'POST').then(res=>{
          console.log(res)
          if (res.code === 20000) {
                    // wx.removeStorageSync('orderId');
                    //地址id
                    wx.setStorageSync('addressId', 0);
                    const orderId = res.data.uubOdId;
                    // pay.payOrder(parseInt(orderId)).then(res => {
                        wx.redirectTo({
                            url: '/pages/payResult/payResult?status=1&orderId=' + orderId
                        });
                    // })
                    // .catch(res => {
                    //     wx.redirectTo({
                    //         url: '/pages/payResult/payResult?status=0&orderId=' + orderId
                    //     });
                    // });
                } else {
                    // util.showErrorToast(res.errmsg);
                    wx.redirectTo({
                      url: '/pages/payResult/payResult?status=0&orderId=' + orderId
                  });
                }
                wx.hideLoading()
        })
      }
        if(safeMethod==1){
          let uandubOrders={
            userId:that.data.userOneList.userId,//下单用户id
            uubOdBusinessId:that.data.goodsOneList.createUser,//商家id
            goodId:that.data.goodsOneList.goodId,//下单商品id
            // uubOdAddress://用户地址
            uubOdActualprice:that.data.sumpriceend,//实付价格
            createUser:that.data.userOneList.userId,
            updateUser:that.data.userOneList.userId,//创建人和修改人
            // safeId://保险id 运费险1 没有是null
          }
          util.request(api.saveOrder,uandubOrders, 'POST').then(res=>{
            console.log(res)
            if (res.code === 20000) {
                      // wx.removeStorageSync('orderId');
                      //地址id
                      wx.setStorageSync('addressId', 0);
                      const orderId = res.data.uubOdId;
                      // pay.payOrder(parseInt(orderId)).then(res => {
                          wx.redirectTo({
                              url: '/pages/payResult/payResult?status=1&orderId=' + orderId
                          });
                      // })
                      // .catch(res => {
                      //     wx.redirectTo({
                      //         url: '/pages/payResult/payResult?status=0&orderId=' + orderId
                      //     });
                      // });
                  } else {
                      // util.showErrorToast(res.errmsg);
                      wx.redirectTo({
                        url: '/pages/payResult/payResult?status=0&orderId=' + orderId
                    });
                  }
                  wx.hideLoading()
          })
        }
        // util.request(api.OrderSubmit, {
        //     addressId: addressId,
        //     postscript: postscript,
        //     freightPrice: freightPrice,
        //     actualPrice: actualPrice,
        //     offlinePay: 0
        // }, 'POST').then(res => {
        //     if (res.errno === 0) {
        //         wx.removeStorageSync('orderId');
        //         wx.setStorageSync('addressId', 0);
        //         const orderId = res.data.orderInfo.id;
        //         pay.payOrder(parseInt(orderId)).then(res => {
        //             wx.redirectTo({
        //                 url: '/pages/payResult/payResult?status=1&orderId=' + orderId
        //             });
        //         }).catch(res => {
        //             wx.redirectTo({
        //                 url: '/pages/payResult/payResult?status=0&orderId=' + orderId
        //             });
        //         });
        //     } else {
        //         util.showErrorToast(res.errmsg);
        //     }
        //     wx.hideLoading()
        // });
    },
    openlineOrder:function(){
      let that=this
      let uandubOrders={
        userId:that.data.userOneList.userId,//下单用户id
        uubOdBusinessId:that.data.goodsOneList.createUser,//商家id
        goodId:that.data.goodsOneList.goodId,//下单商品id
        // uubOdAddress://用户地址
        uubOdActualprice:that.data.sumgoodsprice,//实付价格
        createUser:that.data.userOneList.userId,
        updateUser:that.data.userOneList.userId,//创建人和修改人
    }
    util.request(api.saveOrderyfk,uandubOrders, 'POST').then(res=>{
      console.log(res)
      if (res.code === 20000) {
                // wx.removeStorageSync('orderId');
                //地址id
                wx.setStorageSync('addressId', 0);
                const orderId = res.data.uubOdId;
            } 
            wx.hideLoading()
    })

        wx.navigateTo({
          url: '/pages/payOffline/index',
        });
      // wx.showModal({
      //   title: '提示',  
      //   content: '请先完善个人信息',  
      //   success: function (res) {
      //     if (res.confirm) {//这里是点击了确定以后  
      //       wx.navigateTo({
      //         url: '/pages/ucenter/settings/index',
      //       });
      //     } else {//这里是点击了取消以后  
      //       wx.navigateTo({
      //         url: '/pages/ucenter/settings/index',
      //       });
      //     }
      //   }
      // })
    },
    offlineOrder: function (e) {
        
        if (this.data.addressId <= 0) {
            util.showErrorToast('请选择收货地址');
            return false;
        }
        // let addressId = this.data.addressId;
        // let postscript = this.data.postscript;
        // let freightPrice = this.data.freightPrice;
        // let actualPrice = this.data.actualPrice;
        // util.request(api.OrderSubmit, {
        //     addressId: addressId,
        //     postscript: postscript,
        //     freightPrice: freightPrice,
        //     actualPrice: actualPrice,
        //     offlinePay: 1
        // }, 'POST').then(res => {
        //     if (res.errno === 0) {
        //         wx.removeStorageSync('orderId');
        //         wx.setStorageSync('addressId', 0);
        //         wx.redirectTo({
        //             url: '/pages/payOffline/index?status=1',
        //         })
        //     } else {
        //         util.showErrorToast(res.errmsg);
        //         wx.redirectTo({
        //             url: '/pages/payOffline/index?status=0',
        //         })
        //     }
        // });
    }
})